#include "particleEmitter.h"
#include <time.h>

particleEmitter::particleEmitter(void)
{
	brazierRadius = 15.0;
	
}


particleEmitter::~particleEmitter(void)
{
}


double particleEmitter::getRand(double RANGE_MIN, double RANGE_MAX)
{

  // THIS IS GIVING ME TROUBLE!!!
  //srand(time(0));
 
  return RANGE_MAX*(rand()%100 - 50)/50.0;
}

double particleEmitter::getRand0(double RANGE)
{
  return RANGE*(rand()%100)/100;
}

void particleEmitter::setParticleMode(unsigned mode)
{
        particleMode = mode;
        
	if (particleMode == 1){
	  // smoke
	  genRate = 5;
	  particleLife = 4.0f;
	  hvelRadius = 0.03;
	  velRadius = 0.5f;
	  yOffset = 1.0f;
	  return;
	}
        if (particleMode == 2){
	  // fire
          genRate = 50;
          particleLife = 0.5f;
          hvelRadius = 0.1;
          velRadius = 1.4f;
          yOffset = 0.2f;
	}

	if (particleMode == 3){
          //sparks
	  genRate = 75;
	  particleLife = 0.5f;
	  yOffset = 2.0f;
          velRadius = 0.1f;
          hvelRadius = 1.0f;
	}
}

void particleEmitter::emit(float ElapsedTime)
{
  int HOW_MANY = (int)ceil(ElapsedTime*genRate);
	for (int i=0; i< HOW_MANY; i++){
	  if (particleMode ==3){
		// RANDOMIZE THE X, Z
	        float vOffsetRange = 20.0; // vertical
	        aiVector3D offset = aiVector3D(getRand(-brazierRadius,brazierRadius), getRand(-vOffsetRange, vOffsetRange), getRand(-brazierRadius, brazierRadius));
		
		// RANDOMIZE THE LIFETIME
		 
		// RANDOMIZE THE DIRECTION?
		CannonParticle p;
		p.position = emitPos + offset;
		// RANDOMIZE THE VELOCITY
		p.velocity = aiVector3D(getRand(-hvelRadius, hvelRadius),getRand(-velRadius, velRadius), getRand(-hvelRadius, hvelRadius));
		p.timeLeft = particleLife;
		particles.push_back(p);
	  }
	}
}

void particleEmitter::updateMyParticles(float ElapsedTime)
{
	for (unsigned i=0; i<particles.size(); i++){
		if (particles[i].timeLeft <=0.0f){
			particles.erase(particles.begin() + i);
		}
		// UPDATE PARTICLE POS.
		particles[i].position +=particles[i].velocity*ElapsedTime;
                // UPDATE PARTICLE VEL. (WHEN ACCERLATION IS PRESENT)
		// particles[i].velocity += aiVector3D(0.0f,0.2f*ElapsedTime, 0.0f);
		//UPDATE PARTICLE LIFETIME
		particles[i].timeLeft -= ElapsedTime;
	}
}

